package com.lil.qmui.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;


/**
 * 字符串操作工具包
 * 
 * @author Administrator
 * 
 */
public class StringUtil {
    private final static Pattern emailer = Pattern
            .compile("^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$");
    private final static Pattern phone = Pattern
            .compile("^((13[0-9])|(15[0-9])|(18[0-9]))\\d{8}$");
    private final static Pattern number = Pattern
    		.compile("^[0-9]*$");
    

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss", Locale.getDefault());
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        }
    };

    /**
     * 返回当前系统时间
     */
    public static String getDataTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format, Locale.getDefault());
        return df.format(new Date());
    }

    /**
     * 返回当前系统时间
     */
    public static String getDataTime() {
        return getDataTime("HH:mm");
    }

    /**
     * 毫秒值转换为mm:ss
     * 
     * @author kymjs
     * @param ms
     */
    public static String timeFormat(int ms) {
        StringBuilder time = new StringBuilder();
        time.delete(0, time.length());
        ms /= 1000;
        int s = ms % 60;
        int min = ms / 60;
        if (min < 10) {
            time.append(0);
        }
        time.append(min).append(":");
        if (s < 10) {
            time.append(0);
        }
        time.append(s);
        return time.toString();
    }

    /**
     * 将字符串转位日期类型
     * 
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }
    
    /**
     * @brief 将日期类型转化为字符
     * @details
     * @param date
     * @return
     */
    public static String toTime(Date date){
        return dateFormater.get().format(date);
    }

    /**
     * 判断给定字符串时间是否为今日
     * 
     * @param date
     * @return boolean
     */
    public static boolean isToday(String date) {
        boolean b = false;
        Date time = toDate(date);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判断给定字符串是否空白串 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 判断是不是一个合法的手机格式的号码，不判断长度，仅判断数字格式
     */
    public static boolean isPhoneStyle(String phoneNum) {
        // if (phoneNum == null || phoneNum.trim().length() == 0)
        // return false;
        return phone.matcher(phoneNum).matches();
    }
    
    public static boolean isNumber(String num) {
    	return number.matcher(num).matches();
    }

    /**
     * 判断是不是一个11位长度,并且格式正确有效的手机号码
     */
    public static boolean isPhoneCorrect(String phoneNum) {
        return !TextUtils.isEmpty(phoneNum) && phoneNum.length() == 11 && isNumber(phoneNum);
    }
    
    public static boolean isPhoneCorrect(String phoneNum, Boolean isShowToast) {
    	if (!isShowToast) {
    		return isPhoneCorrect(phoneNum);
    	} 
    	if (TextUtils.isEmpty(phoneNum)) {
    		ToastUtils.showToast("手机号不能为空");
    		return false;
    	} else if (phoneNum.length() != 11 || !isNumber(phoneNum)) {
    		ToastUtils.showToast("请输入正确的手机号");
    		return false;
    	}
    	
    	return true;
    }
    
    /**
     * 判断设备号是否正确
     * @param termID
     * @return
     */
    public static boolean isTermIDCorrect(String termID) {
    	return !TextUtils.isEmpty(termID) && termID.length() == 20;
    }

    /**
     * 字符串转整数
     * 
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整
     * 
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * String转long
     * 
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * String转double
     * 
     * @param obj
     * @return 转换异常返回 0
     */
    public static double toDouble(String obj) {
        try {
            return Double.parseDouble(obj);
        } catch (Exception e) {
        }
        return 0D;
    }

    /**
     * 字符串转布尔
     * 
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }


    /**
     * 获取AppKey
     */
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {

        }
        return apiKey;
    }

    /**
     * 获取手机IMEI码
     */
    public static String getPhoneIMEI(Activity aty) {
        TelephonyManager tm = (TelephonyManager) aty
                .getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    /**
     * MD5加密
     */
    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(
                    string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * KJ加密
     */
    public static String KJencrypt(String str) {
        char[] cstr = str.toCharArray();
        StringBuilder hex = new StringBuilder();
        for (char c : cstr) {
            hex.append((char) (c + 5));
        }
        return hex.toString();
    }

    /**
     * KJ解密
     */
    public static String KJdecipher(String str) {
        char[] cstr = str.toCharArray();
        StringBuilder hex = new StringBuilder();
        for (char c : cstr) {
            hex.append((char) (c - 5));
        }
        return hex.toString();
    }

    public static String formatDate(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
        return format.format(date);
    }
    
    /** 
     * 格式化时间 -- 简化显示，（今天，昨天，日期形式）
     * @param time 
     * @return 
     */  
    public static String formatDate2SimplifyDate(Date time) {
		String pattern = "yyyy年MM月dd日";
		String pattern2 = "MM月dd日";
        SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
        SimpleDateFormat format2 = new SimpleDateFormat(pattern2, Locale.getDefault());
		if (time == null) {
			return "";
		}
		String timeConent = format.format(time);
		String timeConent2 = format2.format(time);
          
        Calendar current = Calendar.getInstance();
        Calendar today = Calendar.getInstance();    //今天
          
        today.set(Calendar.YEAR, current.get(Calendar.YEAR));
        today.set(Calendar.MONTH, current.get(Calendar.MONTH));
        today.set(Calendar.DAY_OF_MONTH,current.get(Calendar.DAY_OF_MONTH));
        //  Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数  
        today.set( Calendar.HOUR_OF_DAY, 0);
        today.set( Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
          
        Calendar yesterday = Calendar.getInstance();    //昨天
          
        yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
        yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
        yesterday.set(Calendar.DAY_OF_MONTH,current.get(Calendar.DAY_OF_MONTH)-1);
        yesterday.set( Calendar.HOUR_OF_DAY, 0);
        yesterday.set( Calendar.MINUTE, 0);
        yesterday.set(Calendar.SECOND, 0);
          
        current.setTime(time);  
          
        if(current.after(today)){  
            return "今天 ";  
        }else if(current.before(today) && current.after(yesterday)){  
            return "昨天 ";  
        }else{  
            if (current.get(Calendar.YEAR) == today.get(Calendar.YEAR)) {
            	return timeConent2;
            }
            return timeConent;  
        }  
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    public static boolean checkPone(String phone) {
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showToast("手机号码不能为空");
            return false;
        } else if (!StringUtil.isPhoneStyle(phone)) {
            ToastUtils.showToast("您输入的是一个无效的手机号码");
            return false;
        }
        return true;
    }

    /**
     * 密码验证
     * 
     * @param passwd
     * @return
     */
    public static boolean isPasswd(String passwd, boolean isShowToast) {
        if (TextUtils.isEmpty(passwd)) {
            if (isShowToast)
                ToastUtils.showToast("密码长度不能低于6位");
            return false;
        } else if (passwd.length() < 6) {
            if (isShowToast)
                ToastUtils.showToast("密码长度不能低于6位");
            return false;
        } else if (passwd.length() > 12) {
            if (isShowToast)
                ToastUtils.showToast("密码长度不能大于12位");
            return false;
        }
        return true;
    }
    
    /**
     * wifi密码验证
     * 
     * @param passwd
     * @return
     */
    public static boolean isWifiPassword(String passwd, boolean isShowToast) {
        if (TextUtils.isEmpty(passwd)) {
            if (isShowToast)
                ToastUtils.showToast("密码长度不能低于8位");
            return false;
        } else if (passwd.length() < 8) {
            if (isShowToast)
                ToastUtils.showToast("密码长度不能低于8位");
            return false;
        } else if (passwd.length() > 63) {
            if (isShowToast)
                ToastUtils.showToast("密码长度不能大于63位");
            return false;
        }
        return true;
    }

    public static boolean isSamePassowrd(String fPassword, String sPassword) {
        if (TextUtils.isEmpty(fPassword) || TextUtils.isEmpty(sPassword)) {
            ToastUtils.showToast("密码不能为空");
            return false;
        } else if (!fPassword.equalsIgnoreCase(sPassword)) {
            ToastUtils.showToast("密码前后不一致，请重新输入");
            return false;
        } else {
            return true;
        }
    }

    public static boolean isSamePassowrd(String fPassword, String sPassword,
                                         boolean isShowToast) {
        if (TextUtils.isEmpty(fPassword) || TextUtils.isEmpty(sPassword)) {
            if (isShowToast) {
                ToastUtils.showToast("密码不能为空");
            }
            return false;
        } else if (!fPassword.equalsIgnoreCase(sPassword)) {
            if (isShowToast) {
                ToastUtils.showToast("密码前后不一致，请重新输入");
            }
            return false;
        } else {
            return true;
        }
    }

    /**
     * 验证码验证
     * 
     * @param verify
     * @return
     */
    public static boolean isVerifyCode(String verify) {
        if (TextUtils.isEmpty(verify)) {
            ToastUtils.showToast("验证码不能为空");
            return false;
        }
        return true;
    }

    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    public static String getDate(long milliseconds) {
        String result = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        Date date = new Date(milliseconds * 1000);
        result = sdf.format(date);
        return result;
    }

    public static String getMKBSizeFromBt(int packageSize) {
        String mbsize = "未知大小";
        DecimalFormat df = new DecimalFormat("###.##");
        packageSize = Math.abs(packageSize);
        float f;
        if (packageSize < 1024 * 1024) {
            f = (float) ((float) packageSize / (float) 1024);
            mbsize = (df.format(f) + "KB");
        } else {
            f = (float) ((float) packageSize / (float) (1024 * 1024));
            mbsize = (df.format(f) + "MB");
        }
        return mbsize;
    }

    public static String getMKBSizeFromKB(int packageSize) {
        String mbsize = "未知大小";
        DecimalFormat df = new DecimalFormat("###.##");
        packageSize = Math.abs(packageSize);
        float f;
        if (packageSize < 1024) {
            f = packageSize;
            mbsize = (df.format(f) + "KB");
        } else {
            f = (float) ((float) packageSize / (float) (1024));
            mbsize = (df.format(f) + "MB");
        }
        return mbsize;
    }

    public static String getBSizeFromKB(int packageSize) {
        String bsize = "未知大小";
        DecimalFormat df = new DecimalFormat("###.##");
        packageSize = Math.abs(packageSize);
        float f;
        f = (float) ((float) packageSize * (float) (1024));
        bsize = (df.format(f));
        return bsize;
    }

    /**
     * m转km
     * @param meter
     * @return
     */
	public static String getKMFromM(String meter) {
		String kmSize = "未知";
		if (TextUtils.isEmpty(meter)) {
			return kmSize;
		}
		int m;
		try {
			m = Integer.valueOf(meter);
			m = Math.abs(m);
			float f;
			f = (float) ((float) m / (float) (1000));
			kmSize = f + "km";
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return kmSize;
	}

    /**
     * 毫秒转日期
     * @param time
     * @return
     */
	public static String getTime(String time) {
		String result = "";
		try {
//			int milliseconds = Integer.parseInt(time);
			long milliseconds = Long.parseLong(time);
			SimpleDateFormat sdf = new SimpleDateFormat("yyy/MM/dd HH:mm", Locale.getDefault());
			Date date = new Date(milliseconds * 1000);
			result = sdf.format(date);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static String getConsumeTime(int consumeTime) {
		// String result = "";
		// try {
		// int milliseconds = Integer.parseInt(consumeTime);
		// SimpleDateFormat sdf = new SimpleDateFormat("HH时mm分",
		// Locale.getDefault());
		// Date date = new Date(milliseconds * 1000);
		// result = sdf.format(date);
		// } catch (NumberFormatException e) {
		// e.printStackTrace();
		// }
		// return result;

		String timeStr = null;
		int hour = 0;
		int minute = 0;
		int second = 0;
		if (consumeTime <= 0) {
			return "00分00秒";
		} else {
			minute = consumeTime / 60;
			if (minute < 60) {
				second = consumeTime % 60;
				timeStr = unitFormat(minute) + "分" + unitFormat(second) +"秒";
			} else {
				hour = minute / 60;
				if (hour > 99) {
					return "99:59:59";
				}
				minute = minute % 60;
				second = consumeTime - hour * 3600 - minute * 60;
				timeStr = unitFormat(hour) + "时" + unitFormat(minute) + "分" /*+ unitFormat(second)*/;
			}
		}
		return timeStr;
	}
	
	public static String unitFormat(int i) {
		String retStr = null;
		if (i >= 0 && i < 10) {
			retStr = "0" + Integer.toString(i);
		} else {
			retStr = "" + i;
		}
		return retStr;
	}
}
